// 视频选择器策略
const VIDEO_SELECTORS = {
    'youtube.com': 'video.html5-main-video',
    'bilibili.com': 'video.bilibili-player-video'
};

// 视频元素查找函数
function findVideoElement() {
    // 通用视频选择器
    const commonSelectors = [
        'video',
        'video#video-player',
        '.bilibili-player-video video', // Bilibili 特定
        '#player_placeholder video',    // Bilibili 特定
        '.player-wrap video',          // Bilibili 特定
        '#bilibili-player video'       // Bilibili 特定
    ];

    // 尝试所有选择器
    for (let selector of commonSelectors) {
        const video = document.querySelector(selector);
        if (video && video instanceof HTMLVideoElement) {
            return video;
        }
    }

    // 如果常规选择器失败，尝试查找所有video元素
    const allVideos = document.getElementsByTagName('video');
    if (allVideos.length > 0) {
        // 返回第一个正在播放的视频，如果没有则返回第一个视频
        const playingVideo = Array.from(allVideos).find(v => !v.paused) || allVideos[0];
        if (playingVideo instanceof HTMLVideoElement) {
            return playingVideo;
        }
    }

    // 如果是Bilibili，尝试通过iframe查找
    if (window.location.hostname.includes('bilibili.com')) {
        const iframes = document.getElementsByTagName('iframe');
        for (let iframe of iframes) {
            try {
                const iframeVideo = iframe.contentDocument?.querySelector('video');
                if (iframeVideo && iframeVideo instanceof HTMLVideoElement) {
                    return iframeVideo;
                }
            } catch (e) {
                console.log('Cannot access iframe content:', e);
            }
        }
    }

    return null;
}

// 获取当前网站的视频元素
function getVideoElement() {
    const hostname = window.location.hostname;
    let selector = '';
    
    if (hostname.includes('youtube.com')) {
        selector = VIDEO_SELECTORS['youtube.com'];
    } else if (hostname.includes('bilibili.com')) {
        selector = VIDEO_SELECTORS['bilibili.com'];
    }
    
    const video = document.querySelector(selector);
    if (!video) {
        // 如果没有找到视频，等待一段时间后重试
        return new Promise((resolve) => {
            const observer = new MutationObserver((mutations, obs) => {
                const video = document.querySelector(selector);
                if (video) {
                    obs.disconnect();
                    resolve(video);
                }
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });

            // 设置超时，避免无限等待
            setTimeout(() => {
                observer.disconnect();
                resolve(null);
            }, 10000);
        });
    }
    return video;
}

// 复制到剪贴板
async function copyToClipboard(dataUrl) {
    try {
        // 创建一个临时的 canvas 元素
        const img = new Image();
        img.crossOrigin = "anonymous";  // 允许跨域
        
        await new Promise((resolve, reject) => {
            img.onload = resolve;
            img.onerror = reject;
            img.src = dataUrl;
        });

        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);

        // 尝试使用 canvas 的 toBlob 方法
        const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
        
        // 请求剪贴板写入权限
        try {
            await navigator.permissions.query({name: 'clipboard-write'});
        } catch (e) {
            console.log('Clipboard permissions API not available, trying direct write');
        }

        // 尝试写入剪贴板
        try {
            await navigator.clipboard.write([
                new ClipboardItem({
                    'image/png': blob
                })
            ]);
            showToast('已复制到剪贴板');
            return true;
        } catch (e) {
            console.log('Modern clipboard API failed, trying fallback', e);
            
            // 回退方案：使用 execCommand
            canvas.style.position = 'fixed';
            canvas.style.left = '-9999px';
            document.body.appendChild(canvas);
            
            try {
                canvas.focus();
                const success = document.execCommand('copy');
                document.body.removeChild(canvas);
                if (success) {
                    showToast('已复制到剪贴板');
                    return true;
                }
            } catch (err) {
                console.error('execCommand failed:', err);
            } finally {
                if (document.body.contains(canvas)) {
                    document.body.removeChild(canvas);
                }
            }
        }

        // 如果都失败了，尝试最后的回退方案
        try {
            const tempInput = document.createElement('textarea');
            tempInput.value = dataUrl;
            document.body.appendChild(tempInput);
            tempInput.select();
            const success = document.execCommand('copy');
            document.body.removeChild(tempInput);
            if (success) {
                showToast('已复制到剪贴板');
                return true;
            }
        } catch (err) {
            console.error('All clipboard methods failed:', err);
            showToast('复制失败', 'error');
            return false;
        }
    } catch (error) {
        console.error('Error copying to clipboard:', error);
        showToast('复制失败: ' + error.message, 'error');
        return false;
    }
}

// 捕获视频帧
async function captureVideoFrame() {
    const video = findVideoElement();
    if (!video) {
        throw new Error('No video element found');
    }

    // 等待视频元数据加载
    return new Promise((resolve, reject) => {
        if (video.readyState >= 2) {
            processVideoFrame(video, resolve, reject);
        } else {
            video.addEventListener('loadeddata', () => {
                processVideoFrame(video, resolve, reject);
            }, { once: true });
        }
    });
}

// 获取视频信息
function getVideoInfo() {
    const video = findVideoElement();
    if (!video) {
        return { success: false };
    }

    let title = '';
    let platform = '';

    if (window.location.hostname.includes('youtube.com')) {
        const selectors = [
            'h1.ytd-video-primary-info-renderer',
            'h1.title.style-scope.ytd-video-primary-info-renderer',
            '#container h1.title'
        ];
        
        for (let selector of selectors) {
            const element = document.querySelector(selector);
            if (element) {
                title = element.textContent.trim();
                break;
            }
        }
        platform = 'YouTube';
    } else if (window.location.hostname.includes('bilibili.com')) {
        const selectors = [
            'h1.video-title',
            '.tit',
            '.title',
            '.video-title',
            '.title-text',
            '.media-title'
        ];
        
        for (let selector of selectors) {
            const element = document.querySelector(selector);
            if (element) {
                title = element.textContent.trim();
                break;
            }
        }
        platform = 'Bilibili';
    }

    return {
        success: true,
        title: title || '未知标题',
        currentTime: video.currentTime,
        duration: video.duration,
        platform: platform
    };
}

// 确保页面加载完成后再初始化消息监听
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeMessageListener);
} else {
    initializeMessageListener();
}

function initializeMessageListener() {
    // 监听来自 background script 的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        if (request.action === 'ping') {
            // 响应 ping 消息，表明内容脚本已加载
            sendResponse({ status: 'ok' });
            return false;
        }
        
        if (request.action === 'captureFrame') {
            captureVideoFrame()
                .then(frameData => sendResponse({ success: true, frameData }))
                .catch(error => sendResponse({ success: false, error: error.message }));
            return true; // 保持消息通道开放以进行异步响应
        }
        
        if (request.action === 'copyToClipboard') {
            copyToClipboard(request.dataUrl)
                .then(success => sendResponse({ success }))
                .catch(error => sendResponse({ success: false, error: error.message }));
            return true;
        }
        
        if (request.action === 'getVideoInfo') {
            const videoInfo = getVideoInfo();
            sendResponse({ success: true, data: videoInfo });
        }
        return true; // 保持消息通道开放
    });
}

// 创建并注入样式
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = chrome.runtime.getURL('toast.css');
document.head.appendChild(link);

// 显示提示信息
function showToast(message, type = 'success') {
    // 移除现有的提示
    const existingToast = document.querySelector('.clip-toast');
    if (existingToast) {
        existingToast.remove();
    }

    // 创建新的提示元素
    const toast = document.createElement('div');
    toast.className = `clip-toast ${type}`;
    
    // 创建图标
    const icon = document.createElement('div');
    icon.className = 'icon';
    
    if (type === 'success') {
        icon.innerHTML = `
            <svg width="20" height="20" viewBox="0 0 20 20">
                <path class="checkmark" fill="none" d="M4 10l4 4 8-8" />
            </svg>`;
    } else {
        icon.innerHTML = `
            <svg width="20" height="20" viewBox="0 0 20 20">
                <path fill="white" d="M10 0C4.48 0 0 4.48 0 10s4.48 10 10 10 10-4.48 10-10S15.52 0 10 0zm1 15H9v-2h2v2zm0-4H9V5h2v6z"/>
            </svg>`;
    }

    // 创建消息文本
    const text = document.createElement('span');
    text.textContent = message;

    // 组装提示元素
    toast.appendChild(icon);
    toast.appendChild(text);
    document.body.appendChild(toast);

    // 触发动画
    setTimeout(() => toast.classList.add('show'), 10);

    // 设置自动消失
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 2000);
}

async function processVideoFrame(video, resolve, reject) {
    try {
        // 获取当前设置
        const { settings = {} } = await chrome.storage.sync.get('settings');
        const imageFormat = settings.imageFormat || 'png';
        const jpegQuality = parseFloat(settings.jpegQuality || '0.85');

        // 创建 canvas 并设置尺寸
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 在 canvas 上绘制当前视频帧
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 根据设置生成图片
        const mimeType = `image/${imageFormat}`;
        const dataUrl = canvas.toDataURL(mimeType, 
            imageFormat === 'jpeg' ? jpegQuality : undefined);

        // 返回图像数据
        resolve({
            dataUrl,
            title: document.title,
            platform: window.location.hostname.includes('youtube.com') ? 'youtube' : 'bilibili'
        });

        // 添加到历史记录
        chrome.runtime.sendMessage({
            action: 'addToHistory',
            data: {
                dataUrl,
                title: document.title,
                platform: window.location.hostname.includes('youtube.com') ? 'youtube' : 'bilibili',
                timestamp: new Date().toISOString()
            }
        });
    } catch (error) {
        reject(error);
    }
}
